<?php

namespace app\common\model\dealer;

use app\common\model\BaseModel;
use app\common\model\User as userModel;
/**
 * 分销商推荐关系模型
 * Class Referee
 * @package app\common\model\dealer
 */
class Referee extends BaseModel
{
    protected $name = 'dealer_referee';

    /**
     * 关联用户表
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('app\api\model\User');
    }

    /**
     * 关联分销商用户表
     * @return \think\model\relation\BelongsTo
     */
    public function dealer()
    {
        return $this->belongsTo('User')->where('is_delete', '=', 0);
    }

    /**
     * 获取上级用户id
     * @param $user_id
     * @param $level
     * @param bool $is_dealer 必须是分销商
     * @return bool|mixed
     * @throws \think\exception\DbException
     */
    public static function getRefereeUserId($user_id, $level, $is_dealer = false)
    {
        $dealer_id = (new self)->where(compact('user_id', 'level'))
            ->value('dealer_id');
        if (!$dealer_id) return 0;
        return $is_dealer ? (User::isDealerUser($dealer_id) ? $dealer_id : 0) : $dealer_id;
    }

    /**
     * 获取我的团队列表
     * @param $user_id
     * @param int $level
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($user_id, $level = -1)
    {
        $level > -1 && $this->where('referee.level', '=', $level);
        return $this->with(['dealer', 'user'])
            ->alias('referee')
            ->field('referee.*')
            ->join('user', 'user.user_id = referee.user_id')
            ->where('referee.dealer_id', '=', $user_id)
            ->where('user.is_delete', '=', 0)
            ->order(['referee.create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
    }

    /**
     * 获取我的级差团队列表
     * @param $user_id
     * @param int $level
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getListLevel($user_id,$user_level_money, $level = -1)
    {
        $level > -1 && $this->where('referee.level', '=', $level);
        //计算总额
        $all = $this->statisticsLevel($user_id,$user_level_money);
        //计算分页数据
        $list = $this->with(['dealer', 'user'])
            ->alias('referee')
            ->field('referee.*')
            ->join('user', 'user.user_id = referee.user_id')
            ->where('referee.dealer_id', '=', $user_id)
            ->where('user.is_delete', '=', 0)
            ->order(['referee.create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
        $list_array = $list->toArray();
        $tem_arr = [];
        foreach ($list_array['data'] as $k=>$v){
            $keys = array_keys($all['level_user']);
            if (in_array($v['user_id'],$keys)){
                $v['level_user'] = $all['level_user'][$v['user_id']];
                $tem_arr[] = $v;
            }
        }
        $list->setItems($tem_arr);
        return ['list'=>$list,'all_royalty'=>$all['all_royalty'],'level'=>$all['level']];
    }

    /**
     * 统计用户总提成及下线数据
     * @param $user_id    用户编号
     * @param $user_level_money  用户累计流水
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function statisticsLevel($user_id,$user_level_money){
        //计算用户所在级别及提成点
        $user_level =  operationlevel($user_level_money);
        //Array ( [level] => 2 [royalty] => 4 )
        $userModel = new userModel();
        //统计下线数据
        $list_level = $userModel->where(['level_id'=>$user_id])->select();
        //临时变量-存储总提成
        $all_royalty = 0;
        //临时变量-存储处理好的下线数据
        $level_array = [];
        //临时变量-存储用户自己业绩
        $self_money = $user_level_money;
        foreach ($list_level as $k=>$v){
            $tem_level = operationlevel($v['level_money']);
            $self_money = $self_money - $v['level_money'];
            //用户级差提成
            if ($user_level['level'] - $tem_level['level'] > 0){
                $tem_level['user_level_money'] = $v['level_money']*($user_level['royalty']-$tem_level['royalty'])*0.0001;
            }else{
                $tem_level['user_level_money'] = 0;
            }
            //统计累计提成
            $all_royalty = $all_royalty+$tem_level['user_level_money'];
            //将数据存储
            $level_array[$v['user_id']] =  $tem_level;
        }
        return ['all_royalty'=>$all_royalty+($user_level['royalty']*$self_money*0.0001),'level_user'=>$level_array,'level'=>$user_level['level']];
    }
}